import ConfirmModal from '@/components/ConfirmModal';
import PlaceHolderCpn from '@/components/PlaceHolderCpn';
import { Auths, Role } from '@/utils/types.d';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { Tag } from 'antd';
import { useModel, useHistory } from 'umi';
import CreateUser from './components/CreateUser';
import UpdateUser from './components/UpdateUser';
import UserDetail from './components/UserDetail';
import { queryUsers, removeUser } from './service';
import type { UserTableListItem } from './types';

export default () => {
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser;
  const auths = currUser?.auth ? new Set(currUser.auth.systemUser || []) : new Set();
  const ownerId = currUser?.ownerId || '';
  const userRole = currUser?.role;
  const history = useHistory();
  const RoleEnum =
    userRole === Role.ADMIN
      ? {
          0: <Tag color="red">系统管理</Tag>,
          1: <Tag color="blue">企业管理</Tag>,
          2: <Tag color="green">企业员工</Tag>,
        }
      : {
          1: <Tag color="red">企业管理</Tag>,
          2: <Tag color="blue">企业员工</Tag>,
        };
  const ifCreate = auths.has(Auths.CREATE);
  const ifModify = auths.has(Auths.MODIFY);
  const ifDelete = auths.has(Auths.DELETE);
  const columns: ProColumns<UserTableListItem>[] = [
    {
      title: 'id',
      hideInTable: true,
      hideInSearch: true,
      dataIndex: '_id',
    },
    {
      title: '用户名称',
      width: 120,
      dataIndex: 'userName',
      render: (_, record, x, action) => (
        <UserDetail reload={() => action?.reload()} text={record.userName} user={record} />
      ),
    },
    {
      title: '用户账号',
      width: 120,
      dataIndex: 'account',
    },
    {
      title: '用户角色',
      width: 70,
      dataIndex: 'role',
      align: 'center',
      hideInSearch: true,
      valueEnum: RoleEnum,
    },
    {
      title: '创建时间',
      width: 200,
      align: 'center',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '权限管理',
      width: 120,
      align: 'center',
      dataIndex: 'auth',
      hideInSearch: true,
      render: (_, record) =>
        userRole >= record.role ? (
          <PlaceHolderCpn />
        ) : (
          // <AuthEdit authId={record.auth} ownerName={record.ownerName} />
          <a
            onClick={() => {
              history.push({
                pathname: '/system-user/auth',
                state: {
                  authId: record.auth,
                  ownerName: record.ownerName,
                },
              });
            }}
          >
            权限管理
          </a>
        ),
    },
    {
      title: '操作',
      width: 100,
      align: 'center',
      key: 'option',
      fixed: 'right',
      valueType: 'option',
      render: (_, record, x, action) => [
        <UserDetail
          user={record}
          key={`${record._id}_userdetail`}
          reload={() => action?.reload()}
        />,
        ifModify && <UpdateUser func={() => action?.reload()} user={record} />,
        ifDelete && record.role !== Role.ADMIN && record._id !== currUser?.id && (
          <ConfirmModal
            reload={() => action?.reload()}
            operFunc={async () => await removeUser(record._id)}
            danger={record.role === Role.ENTERPRISE}
            text={
              record.role === Role.ENTERPRISE
                ? '正在删除[企业管理者]，该操作会删除相关企业所有人员，请慎重操作！'
                : undefined
            }
          />
        ),
      ],
    },
  ];
  return (
    <PageHeaderWrapper
      header={{
        title: '',
        subTitle: '用户列表',
        breadcrumb: {
          routes: [
            {
              path: '/',
              breadcrumbName: '首页',
            },
            {
              path: '/system-user',
              breadcrumbName: '用户管理',
            },
            {
              path: '/system-user/list',
              breadcrumbName: '用户列表',
            },
          ],
        },
      }}
    >
      <ProTable<UserTableListItem>
        rowKey="id"
        scroll={{ x: true }}
        style={{ whiteSpace: 'nowrap' }}
        columns={columns}
        columnEmptyText="暂无数据"
        params={{
          ownerId: ownerId === 'admin' ? '' : ownerId,
        }}
        debounceTime={300}
        request={async (param, sort) => {
          const res = await queryUsers(param, sort);
          return res;
        }}
        dateFormatter="string"
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          defaultPageSize: 10,
          size: 'default',
        }}
        toolBarRender={(action) =>
          ifCreate
            ? [
                <CreateUser
                  key="create_user"
                  func={() => {
                    action?.reload();
                  }}
                />,
              ]
            : []
        }
      />
    </PageHeaderWrapper>
  );
};
